package win.somereason.test.baseline_web.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import win.somereason.test.baseline_web.dao.SecUserMapper;
import win.somereason.test.baseline_web.entity.SecUser;
import win.somereason.test.baseline_web.entity.SecUserDetails;

/**
 * Created by Qingsheng.Sun on 2018/3/30.
 */
public class SecUserDetailsService implements UserDetailsService {
    @Autowired
    SecUserMapper secUserMapper;

    public UserDetails loadUserByUsername(String loginInfo) throws UsernameNotFoundException {
        SecUser user = loginInfo.contains("@") ? secUserMapper.getUserByEmail(loginInfo) : secUserMapper.getUserByName(loginInfo);

        if (user == null)
            throw new UsernameNotFoundException(String.format("User info '%s' not found", loginInfo));


        SecUserDetails details = new SecUserDetails();
        details.setUserId(user.getSecUserId());
        details.setPassword(user.getSecPassword());
        details.setUsername(user.getName());
        details.setAccountNonExpired(true);
        details.setAccountNonLocked(true);
        details.setCredentialsNonExpired(true);
        details.setEnabled(true);

        return details;
    }

}
